package com.woniuxy.rabbit.collection;

import com.woniuxy.rabbit.config.MQConfig;
import com.woniuxy.rabbit.form.UserRegMSG;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@Slf4j
public class UserCollection {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitTemplate.ConfirmCallback regConfirmCallback;

    @GetMapping("login")
    public String login(String username,String password){
        log.info("进入登录：{}",username);
        UserRegMSG userRegMSG = new UserRegMSG();
        userRegMSG.setId(1);
        userRegMSG.setName(username);
        userRegMSG.setDate(new Date());
        rabbitTemplate.setConfirmCallback(regConfirmCallback);
        rabbitTemplate.convertAndSend(MQConfig.USER_EXCHANGE,MQConfig.USER_BINDING,userRegMSG
                ,new CorrelationData("666"));

        return "success";
    }

    @GetMapping("order")
    public String order(int id){
        log.info("创建订单：{}",id);
        UserRegMSG userRegMSG = new UserRegMSG();
        userRegMSG.setId(1);
        userRegMSG.setName("订单");
        userRegMSG.setDate(new Date());
//        rabbitTemplate.setConfirmCallback(regConfirmCallback);
        rabbitTemplate.convertAndSend(MQConfig.USER_EXCHANGE,MQConfig.USER_BINDING,userRegMSG
                , message -> {
                    MessageProperties properties = message.getMessageProperties();
                    //投递模式
                    properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    //过期时间
                    properties.setExpiration(""+5*1000);
                    //设置ID
                    properties.setCorrelationId(id+"");
                    return message;
                });

        return "success";
    }
}
